<template>
  <div v-if="visible" class="share-modal-overlay" @click="handleOverlayClick">
    <div class="share-modal" @click.stop>
      <!-- 弹窗头部 -->
      <div class="modal-header">
        <div class="header-left">
          <el-icon @click="handleClose" class="close-icon"><Close /></el-icon>
          <span class="modal-title">分享你的生活</span>
        </div>
      </div>
      
      <!-- 弹窗内容 -->
      <div class="modal-content">
        <!-- 用户信息展示 -->
        <div class="user-info-section">
          <div class="user-avatar">
            <img :src="userInfo.avatar" :alt="userInfo.name" />
          </div>
          <div class="user-details">
            <h4 class="user-name">{{ userInfo.name }}</h4>
            <p class="user-subtitle">分享你的精彩瞬间</p>
          </div>
        </div>

        <!-- 分享内容输入 -->
        <div class="content-section">
          <h4 class="section-subtitle">分享内容</h4>
          <el-input 
            v-model="shareContent.content" 
            type="textarea" 
            placeholder="分享你的想法、生活点滴或有趣的事情..."
            :rows="4"
            maxlength="500"
            show-word-limit
            class="content-textarea"
          />
        </div>

        <!-- 图片上传区域 -->
        <div class="image-upload-section">
          <h4 class="section-subtitle">添加图片</h4>
          <div class="upload-area">
            <!-- 已上传的图片预览 -->
            <div v-if="shareContent.images.length > 0" class="image-preview-grid">
              <div 
                v-for="(image, index) in shareContent.images" 
                :key="index"
                class="image-preview-item"
              >
                <img :src="image.url" :alt="`图片${index + 1}`" class="preview-image" />
                <div class="image-actions">
                  <el-icon @click="previewImage(image.url)" class="preview-icon"><Search /></el-icon>
                  <el-icon @click="removeImage(index)" class="remove-icon"><Delete /></el-icon>
                </div>
              </div>
            </div>
            
            <!-- 上传按钮 -->
            <div 
              v-if="shareContent.images.length < 9" 
              class="upload-button"
              @click="triggerFileUpload"
            >
              <el-icon class="upload-icon"><Plus /></el-icon>
              <span class="upload-text">添加图片</span>
              <span class="upload-hint">最多9张</span>
            </div>
            
            <!-- 隐藏的文件输入 -->
            <input 
              ref="fileInput"
              type="file" 
              multiple 
              accept="image/*"
              @change="handleFileUpload"
              style="display: none"
            />
          </div>
        </div>

        <!-- 话题标签 -->
        <div class="topic-section">
          <h4 class="section-subtitle">添加话题</h4>
          <div class="topic-tags">
            <div 
              v-for="(topic, index) in availableTopics" 
              :key="index"
              class="topic-tag"
              :class="{ active: shareContent.topics.includes(topic) }"
              @click="toggleTopic(topic)"
            >
              #{{ topic }}
            </div>
          </div>
        </div>

        <!-- 隐私设置 -->
        <div class="privacy-section">
          <h4 class="section-subtitle">隐私设置</h4>
          <el-radio-group v-model="shareContent.privacy" class="privacy-options">
            <el-radio value="public">公开</el-radio>
            <el-radio value="friends">仅好友可见</el-radio>
            <el-radio value="private">仅自己可见</el-radio>
          </el-radio-group>
        </div>
      </div>

      <!-- 弹窗底部按钮 -->
      <div class="modal-footer">
        <el-button class="cancel-btn" @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          class="submit-btn" 
          @click="() => { console.log('按钮被点击了！'); handleSubmit(); }"
          :disabled="!shareContent.content.trim()"
        >
          发布分享
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, inject, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Close, Plus, Search, Delete } from '@element-plus/icons-vue'
import { createPostApi } from '@/api/discover'
import { useUserStore } from '@/stores/user'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

// 调试props
console.log('ShareModal props:', props)
console.log('ShareModal visible:', props.visible)

const emit = defineEmits(['close', 'submit'])

// 注入刷新方法
const refreshPostList = inject('refreshPostList', null)

// 用户store
const userStore = useUserStore()

// 用户信息
const userInfo = reactive({
  name: userStore.userInfo?.name || '谷粒用户',
  avatar: userStore.userInfo?.avatar || '/src/assets/imgs/avatar_login.png'
})

// 监听用户信息变化
watch(() => userStore.userInfo, (newUserInfo) => {
  if (newUserInfo) {
    userInfo.name = newUserInfo.name || '谷粒用户'
    userInfo.avatar = newUserInfo.avatar || '/src/assets/imgs/avatar_login.png'
  }
}, { deep: true })

// 分享内容
const shareContent = reactive({
  content: '',
  images: [],
  topics: [],
  privacy: 'public'
})

// 可用话题
const availableTopics = ref([
  '谷粒生活',
  '合租日常',
  '美食分享',
  '旅行记录',
  '工作心得',
  '学习笔记',
  '心情随笔',
  '好物推荐'
])

// 文件输入引用
const fileInput = ref(null)

// 触发文件上传
const triggerFileUpload = () => {
  fileInput.value?.click()
}

// 处理文件上传
const handleFileUpload = async (event) => {
  const files = Array.from(event.target.files)
  
  if (files.length === 0) return
  
  // 检查文件数量限制
  if (shareContent.images.length + files.length > 9) {
    ElMessage.warning('最多只能上传9张图片')
    return
  }
  
  // 检查文件类型和大小
  const validFiles = files.filter(file => {
    if (!file.type.startsWith('image/')) {
      ElMessage.warning(`文件 ${file.name} 不是图片格式`)
      return false
    }
    if (file.size > 5 * 1024 * 1024) { // 5MB
      ElMessage.warning(`文件 ${file.name} 超过5MB限制`)
      return false
    }
    return true
  })
  
  // 转换为base64并添加到图片列表
  const imagePromises = validFiles.map(file => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = (e) => {
        resolve({
          url: e.target.result,
          file: file,
          name: file.name
        })
      }
      reader.onerror = reject
      reader.readAsDataURL(file)
    })
  })
  
  try {
    const imageResults = await Promise.all(imagePromises)
    shareContent.images.push(...imageResults)
    console.log('图片上传完成，当前图片数量:', shareContent.images.length)
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败')
  }
  
  // 清空文件输入
  event.target.value = ''
}

// 移除图片
const removeImage = (index) => {
  shareContent.images.splice(index, 1)
}

// 预览图片
const previewImage = (url) => {
  ElMessageBox.alert('', '图片预览', {
    dangerouslyUseHTMLString: true,
    customClass: 'image-preview-dialog',
    showClose: true,
    showConfirmButton: false,
    message: `<img src="${url}" style="max-width: 100%; max-height: 80vh; object-fit: contain;" />`
  })
}

// 切换话题
const toggleTopic = (topic) => {
  const index = shareContent.topics.indexOf(topic)
  if (index > -1) {
    shareContent.topics.splice(index, 1)
  } else {
    if (shareContent.topics.length < 5) {
      shareContent.topics.push(topic)
    } else {
      ElMessage.warning('最多只能选择5个话题')
    }
  }
}

// 提交分享
const handleSubmit = async () => {
  console.log('=== 开始执行分享提交 ===')
  console.log('分享内容:', shareContent.content)
  console.log('内容是否为空:', !shareContent.content.trim())
  console.log('图片列表:', shareContent.images)
  console.log('话题列表:', shareContent.topics)
  console.log('隐私设置:', shareContent.privacy)
  
  if (!shareContent.content.trim()) {
    console.log('内容为空，停止执行')
    ElMessage.warning('请输入分享内容')
    return
  }
  
  // 检查图片是否还在上传中
  if (shareContent.images.some(img => !img.url)) {
    ElMessage.warning('图片还在上传中，请稍候...')
    return
  }
  
  try {
    ElMessage.info('正在发布分享，请稍候...')
    
    // 构建分享数据 - 匹配API文档格式
    const postData = {
      content: shareContent.content,
      images: shareContent.images.map(img => img.url).filter(url => url), // 过滤掉空值
      topics: shareContent.topics,
      privacy: shareContent.privacy
    }
    
    // 验证图片数据
    if (postData.images.length === 0 && shareContent.images.length > 0) {
      console.error('图片数据丢失！原始图片:', shareContent.images)
      ElMessage.error('图片处理失败，请重新选择图片')
      return
    }
    
    console.log('提交分享数据:', postData)
    console.log('图片数据详情:', shareContent.images)
    console.log('图片URLs:', shareContent.images.map(img => img.url))
    console.log('图片数量:', shareContent.images.length)
    console.log('图片数据类型检查:', shareContent.images.map(img => ({
      hasUrl: !!img.url,
      urlType: typeof img.url,
      urlLength: img.url ? img.url.length : 0,
      isBase64: img.url ? img.url.startsWith('data:image/') : false
    })))
    console.log('发送API请求到: api/discover/posts')
    
    // 发送API请求
    const response = await createPostApi(postData)
    
    console.log('分享API响应:', response)
    console.log('响应类型:', typeof response)
    console.log('响应是否为对象:', typeof response === 'object')
    if (response && typeof response === 'object') {
      console.log('响应键:', Object.keys(response))
    }
    
    // 简化响应检查 - 只要没有错误就认为成功
    // ElMessage.success('分享发布成功！')
    emit('submit', postData)
    resetForm()
    emit('close')
    
    // 刷新帖子列表
    if (refreshPostList) {
      refreshPostList()
    }
  } catch (error) {
    console.error('发布分享失败:', error)
    ElMessage.error(error.message || '发布失败，请检查网络连接')
  }
}

// 重置表单
const resetForm = () => {
  shareContent.content = ''
  shareContent.images = []
  shareContent.topics = []
  shareContent.privacy = 'public'
}

// 关闭弹窗
const handleClose = () => {
  resetForm()
  emit('close')
}

// 点击遮罩层关闭
const handleOverlayClick = () => {
  handleClose()
}
</script>

<style scoped>
.share-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.share-modal {
  background-color: #fff;
  border-radius: 16px;
  width: 100%;
  max-width: 500px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.modal-header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-shrink: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.close-icon {
  font-size: 20px;
  cursor: pointer;
  color: #666;
  transition: color 0.3s ease;
}

.close-icon:hover {
  color: #333;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.modal-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

/* 用户信息样式 */
.user-info-section {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 12px;
}

.user-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 4px 0;
}

.user-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.section-subtitle {
  font-size: 16px;
  font-weight: 600;
  margin: 20px 0 12px;
  color: #333;
}

/* 内容输入样式 */
.content-textarea {
  margin-bottom: 8px;
}

/* 图片上传样式 */
.upload-area {
  margin-bottom: 8px;
}

.image-preview-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-bottom: 16px;
}

.image-preview-item {
  position: relative;
  aspect-ratio: 1;
  border-radius: 8px;
  overflow: hidden;
  background-color: #f5f5f5;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  top: 4px;
  right: 4px;
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-preview-item:hover .image-actions {
  opacity: 1;
}

.preview-icon,
.remove-icon {
  width: 24px;
  height: 24px;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 12px;
}

.remove-icon {
  background-color: rgba(231, 76, 60, 0.8);
}

.upload-button {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #fafafa;
}

.upload-button:hover {
  border-color: #4CAF50;
  background-color: #f0f9f0;
}

.upload-icon {
  font-size: 24px;
  color: #4CAF50;
  margin-bottom: 8px;
  display: block;
}

.upload-text {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.upload-hint {
  font-size: 12px;
  color: #999;
}

/* 话题标签样式 */
.topic-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.topic-tag {
  padding: 6px 12px;
  background-color: #f0f0f0;
  border-radius: 16px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.topic-tag:hover {
  background-color: #e0e0e0;
}

.topic-tag.active {
  background-color: #4CAF50;
  color: white;
  border-color: #4CAF50;
}

/* 隐私设置样式 */
.privacy-options {
  display: flex;
  gap: 16px;
}

/* 弹窗底部按钮样式 */
.modal-footer {
  padding: 16px 20px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.cancel-btn {
  flex: 1;
  height: 44px;
  font-size: 16px;
}

.submit-btn {
  flex: 1;
  height: 44px;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .share-modal-overlay {
    padding: 10px;
  }
  
  .share-modal {
    max-height: 95vh;
  }
  
  .modal-content {
    padding: 16px;
  }
  
  .user-info-section {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }
  
  .user-avatar {
    width: 50px;
    height: 50px;
    margin: 0 auto;
  }
  
  .image-preview-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }
  
  .topic-tags {
    gap: 6px;
  }
  
  .topic-tag {
    font-size: 12px;
    padding: 4px 8px;
  }
  
  .privacy-options {
    flex-direction: column;
    gap: 8px;
  }
  
  .modal-footer {
    padding: 12px 16px;
  }
  
  .cancel-btn,
  .submit-btn {
    height: 40px;
    font-size: 14px;
  }
}
</style>

<style>
/* 图片预览对话框样式 */
.image-preview-dialog .el-message-box__content {
  padding: 0;
  text-align: center;
}
</style>
